package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * Jwt 工具类
 *
 * @author Taeyang
 * @date 2025/3/21
 */
public class JwtUtil {

    // token有效时间
    private static long tokenExpiration = 60 * 60 * 1000L;

    /**
     * 定义密钥
     */
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("Zpxty67CWhtaSCf5Wi6luJEyrQFCSrUf".getBytes());

    /**
     * 生成token
     */
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                // 头
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // 负载
                .setSubject("USER_INFO")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                // 签名
                .signWith(tokenSignKey, SignatureAlgorithm.HS256)
                // 连接
                .compact();
        return token;
    }

    /**
     * 解析token
     */
    public static Claims parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts
                    .parser()
                    .verifyWith(tokenSignKey)
                    .build()
                    .parseSignedClaims(token);

            return claimsJws.getBody();

        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    /**
     * 测试
     */
    public static void main(String[] args) {

        String token = createToken(1L, "admin");
        System.out.println(token);
        Claims claims = parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        System.out.println(userId);
        System.out.println(username);
    }
}
